package com.mapeditor.core 
{
	import AS3Events.AS3EventMessage;
	import AS3Events.AS3EventRouter;
	import com.mapeditor.graph.Container;
	import com.mapeditor.math.Vector3;
	import com.mapeditor.util.GlobalContainer;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.MouseEvent;
	/**
	 * ...
	 * @author SE
	 */
	public class PathFactory extends Sprite
	{
		public var points:Array; 
		public var active:Boolean;
		private static var instance:PathFactory;  
		
		
		function PathFactory():void {
			points = new Array();
			this.active = false;
			this.mouseChildren = false;
			this.mouseEnabled = false;
		}
		
		public static function getInstance():PathFactory
		{
			if (instance == null)  
			{
                instance = new PathFactory();  				
			}
            return instance;  
		}
		
		public function start(stage:Stage,p0:Vector3):void {
			
			this.active = true;
			stage.addEventListener(MouseEvent.MOUSE_MOVE, _selectionChange, false, 0, true);				
			stage.addEventListener(MouseEvent.MOUSE_UP, _selectionUp, false, 0, true);								
			points = new Array();
			points.push(p0);
			
			
		}
		
		public function _selectionChange(e:MouseEvent):void {
			//trace(mouseX + "," + mouseY);
			
			if (points.length <= 0)
				return;
				
			this.drawPath();
			
			graphics.lineStyle(1, 0x0000FF);
			graphics.lineTo(mouseX, mouseY);
		}
		public function drawPath():void
		{
			if (points.length <= 0)
				return;
			var c:Container = Container.getInstance();
			graphics.clear();	
			graphics.lineStyle(1, 0xFF0000);
			
			graphics.moveTo(points[0].x+c.x, points[0].y+c.y)
			for (var i:uint = 1, s:uint = points.length; i < s;i++)
				graphics.lineTo(points[i].x+c.x, points[i].y+c.y);
				
			graphics.lineStyle(1, 0xCCCCCC);
			graphics.lineTo(points[0].x+c.x, points[0].y+c.y);
			
			graphics.moveTo(points[points.length-1].x+c.x, points[points.length-1].y+c.y)
		}
		public function _selectionUp(e:MouseEvent):void {
			var c:Container = Container.getInstance();
			points.push(new Vector3(GlobalContainer.checkPosGrid(mouseX-c.x), GlobalContainer.checkPosGrid(mouseY-c.y)));
			
		}
		
		public function stop(stage:Stage):void {
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, _selectionChange);				
			stage.removeEventListener(MouseEvent.MOUSE_UP, _selectionUp);
			this.active = false;
			drawPath();
		}
			
		
	}
	
}